﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using Conusic;
using Conusic.Properties;

namespace Imager.LastFmAutocomplete
{
    internal class Playlist
    {
        private List<AudioRecord> list;

        public List<AudioRecord> Songlist
        {
            get { return list; }
            private set { list = value; }
        }

        public Playlist(List<AudioRecord> list)
        {
            Songlist = list;
        }

        public Playlist(AudioRecord item)
        {
            list = new List<AudioRecord>();
            list.Add(item);
        }

        public string SaveM3U(string filename = null)
        {
            if (filename == null)
            {
                filename = string.Format("{0}\\{1}.m3u", Path.GetTempPath(), Path.GetRandomFileName());
            }

            using (var writer = new StreamWriter(filename, false))
            {
                // Write M3u File
                writer.Write("#EXTM3U\r\n\r\n");
                int port = Settings.Default.AudioServerPort;
                foreach (var song in list)
                {
                    writer.WriteLine("#EXTINF:{2},{0} - {1}", song.Artist, song.CompositionName, song.Duration);
                    if (song.Url != null)
                    {
                        writer.WriteLine(song.Url);
                    }
                    else
                    {
                        writer.WriteLine("http://127.0.0.1:{1}/?act=saveaudio&request={0}",
                                         HttpUtility.UrlEncode(song.ArtistAndComposition,Encoding.UTF8), port);
                    }
                    writer.WriteLine();
                }
            }
            return filename;
        }
    }
}